'use client'

import { useState } from 'react'
import { VmsCourseSection, VmsCopy } from '@/types/Model'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription} from '@/components/ui/dialog'
import { Plus, FileText, BookOpen } from 'lucide-react'
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core'
import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { toast } from '@/hooks/use-toast'
import SortableSectionCard from './SortableSectionCard'
import EnhancedSectionForm from './EnhancedSectionForm'
import CopySelector from './CopySelector'

// 修改 interface
interface SectionManagerProps {
  sections: VmsCourseSection[]
  copies: VmsCopy[]
  courseId: string
  onSectionsUpdate: (sections: VmsCourseSection[]) => void
  onCreateSection: (sectionData: Partial<VmsCourseSection>) => Promise<void>
  onUpdateSection: (sectionData: Partial<VmsCourseSection>) => Promise<void>  // 添加这一行
  onDeleteSection: (sectionId: string) => Promise<void>
  onCreateFromCopies: (copyIds: string[]) => Promise<void>
}

export default function SectionManager({
  sections,
  copies,
  courseId,
  onSectionsUpdate,
  onCreateSection,
  onUpdateSection,  // 添加这一行
  onDeleteSection,
  onCreateFromCopies
}: SectionManagerProps) {
  const [showSectionForm, setShowSectionForm] = useState(false)
  const [showCopySelector, setShowCopySelector] = useState(false)
  const [editSection, setEditSection] = useState<VmsCourseSection | null>(null)

  // 拖拽排序传感器
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  )

  // 拖拽结束处理
  const handleDragEnd = async (event: DragEndEvent) => {
    const { active, over } = event
  
    if (active.id !== over?.id) {
      const oldIndex = sections.findIndex((section: VmsCourseSection) => section.id === active.id)
      const newIndex = sections.findIndex((section: VmsCourseSection) => section.id === over?.id)
  
      const newSections = arrayMove(sections, oldIndex, newIndex)
      onSectionsUpdate(newSections)
  
      // 更新排序到后端
      try {
        const token = localStorage.getItem('token')
        const response = await fetch(`/api/course/${courseId}/sections/reorder`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            sections: newSections.map((section: VmsCourseSection, index: number) => ({
              id: section.id,
              order: index + 1
            }))
          }),
        })
  
        if (!response.ok) {
          throw new Error('更新排序失败')
        }
  
        toast({
          title: '排序已更新',
          description: '小节排序已成功保存'
        })
      } catch (error) {
        console.error('更新排序失败:', error)
        toast({
          title: '排序更新失败',
          description: '请稍后重试',
          variant: 'destructive'
        })
      }
    }
  }

  // 修改 handleCreateSectionSubmit 函数
  const handleCreateSectionSubmit = async (sectionData: Partial<VmsCourseSection>) => {
    if (editSection) {
      // 编辑现有小节
      await onUpdateSection({ ...sectionData, id: editSection.id })
    } else {
      // 创建新小节
      await onCreateSection(sectionData)
    }
    setShowSectionForm(false)
    setEditSection(null)
  }

  return (
    <div className="mb-8">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold text-slate-900">课程小节</h2>
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={() => setShowCopySelector(true)}
          >
            <FileText className="h-4 w-4 mr-2" />
            从文案创建
          </Button>
          <Button
            onClick={() => setShowSectionForm(true)}
            className="bg-gradient-to-r from-rose-600 to-rose-700 hover:from-rose-700 hover:to-rose-800 text-white"
          >
            <Plus className="h-4 w-4 mr-2" />
            新建小节
          </Button>
        </div>
      </div>

      {sections.length === 0 ? (
        <Card className="border-slate-200/50 shadow-sm bg-white/80 backdrop-blur-sm">
          <CardContent className="py-12 text-center">
            <BookOpen className="h-12 w-12 text-slate-400 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-slate-900 mb-2">暂无课程小节</h3>
            <p className="text-slate-600 mb-4">开始创建您的第一个课程小节</p>
            <Button
              onClick={() => setShowSectionForm(true)}
              className="bg-gradient-to-r from-rose-600 to-rose-700 hover:from-rose-700 hover:to-rose-800 text-white"
            >
              <Plus className="h-4 w-4 mr-2" />
              创建小节
            </Button>
          </CardContent>
        </Card>
      ) : (
        <DndContext
          sensors={sensors}
          collisionDetection={closestCenter}
          onDragEnd={handleDragEnd}
        >
          <SortableContext items={sections.map(s => s.id)} strategy={verticalListSortingStrategy}>
            <div className="space-y-4">
              {sections.map((section, index) => (
                <SortableSectionCard
                  key={section.id}
                  section={section}
                  index={index}
                  courseId={courseId}
                  onDelete={onDeleteSection}
                  onUpdate={onUpdateSection}  // 添加这一行
                />
              ))}
            </div>
          </SortableContext>
        </DndContext>
      )}

      {/* 增强版小节表单对话框 */}
      <Dialog open={showSectionForm} onOpenChange={(open) => {
        if (!open) {
          setShowSectionForm(false)
          setEditSection(null)
        }
      }}>
        <DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editSection ? '编辑小节' : '新建小节'}
            </DialogTitle>
          </DialogHeader>
          <EnhancedSectionForm
            section={editSection}
            onCancel={() => {
              setShowSectionForm(false)
              setEditSection(null)
            }}
            onSubmit={handleCreateSectionSubmit}
          />
        </DialogContent>
      </Dialog>

      {/* 文案选择对话框 */}
      {showCopySelector && (
        <Dialog open={showCopySelector} onOpenChange={setShowCopySelector}>
          <DialogContent className="max-w-4xl max-h-[80vh] overflow-hidden">
            <DialogHeader>
              <DialogTitle>从文案创建小节</DialogTitle>
              <DialogDescription>
                选择要创建小节的文案，支持按项目筛选和搜索
              </DialogDescription>
            </DialogHeader>
            <CopySelector
              copies={copies}
              onCancel={() => setShowCopySelector(false)}
              onSubmit={onCreateFromCopies}
            />
          </DialogContent>
        </Dialog>
      )}
    </div>
  )
}